﻿using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
namespace BlockBreak
{
    public class ClickBlockSystem : ComponentSystem
    {
        int BlockLayerMask = -1;
        protected override void OnUpdate()
        {
#if !UNITY_EDITOR && (UNITY_IOS || UNITY_ANDROID)
  
            MobileInput();   
#else
            DesktopInput();
#endif
        }

        void DesktopInput()
        {
            if (Input.GetMouseButtonUp(0))
            {
                ClickBlock();
            }
        }

        void MobileInput()
        {

            if (Input.touchCount <= 0)
                return;

            // 1个手指触摸屏幕  
            if (Input.touchCount == 1)
            {
                // 手指离开屏幕 判断移动方向  
                if (Input.touches[0].phase == TouchPhase.Ended &&
                    Input.touches[0].phase != TouchPhase.Canceled)
                {
                    ClickBlock();
                }
            }
        }

        void ClickBlock()
        {
            if (BlockLayerMask == -1)
            {
                BlockLayerMask = 1 << (LayerMask.NameToLayer("Block"));
            }
            RaycastHit2D hit;
            hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, BlockLayerMask);
            if (hit)
            {
                var block = hit.collider.gameObject.GetComponent<Block>();
                if (block)
                {
                    var score = Bootstrap.Settings.ClickPower;

                    if (block.Score - score < 0)
                    {
                        score = block.Score;
                        block.Score = 0;
                    }
                    else
                    {
                        block.Score -= score;
                    }
                    ScoreEvent.Trigger(score);
                    SyncBlockScoreTextSystem.SetBlockText(block);
                }
            }
        }
    }
}

